package xin.sparrow.util;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Created by wancheng on 2019/10/22.
 */

public class ShellUtil {

    private static final Logger logger = LoggerFactory.getLogger(ShellUtil.class);

    public static String exec(String command) throws InterruptedException {
        String returnString = "";
        Process pro = null;
        Runtime runTime = Runtime.getRuntime();
        if (runTime == null) {
            System.err.println("Create runtime false!");
        }
        try {
            pro = runTime.exec(command);
            BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                returnString = returnString + line + "\n";
            }
            input.close();
            output.close();
            pro.destroy();
        } catch (IOException ex) {
            logger.error("",ex);
        }
        return returnString;
    }

    public static void callShell(String shellString) {
        try {
            Process process = Runtime.getRuntime().exec(shellString);
            int exitValue = process.waitFor();
            if (0 != exitValue) {
                logger.error("call shell failed. error code is :" + exitValue);
            }
        } catch (Throwable e) {
            logger.error("call shell failed. " + e);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.print(exec("ll /Users/wancheng/evn/workspace"));
    }
}
